import jwt
from datetime import datetime

from rest_framework.exceptions import AuthenticationFailed

from .settingg_manager import jwt_settings
from jwt.exceptions import DecodeError, ExpiredSignatureError, InvalidSignatureError

class TokenManager:
    @classmethod
    def get_token(cls, user):
        # 字典为payload的数据
        payload = {
            'username': user.username,
            'id': user.id,
            # 公共声明
            'exp': datetime.utcnow() + jwt_settings.ACCESS_TOKEN_LIFETIME,  # (Expiration Time) token的过期时间的时间戳
            'iat': datetime.utcnow(),  # (Issued At) 创建时间的时间戳
        }
        jwt_encode = jwt.encode(payload, jwt_settings.SIGNING_KEY, algorithm=jwt_settings.ALGORITHM)
        return jwt_encode

    @classmethod
    def get_payload(cls, token):
        # 解析token成payload
        options = {'verify_exp': True}  # options中verify_exp为Ture，jwt.decode会取出payload中的exp校验时间是否过期
        '''
        if "exp" in payload and options["verify_exp"]:
            self._validate_exp(payload, now, leeway)
        '''
        try:
            payload = jwt.decode(token, jwt_settings.SIGNING_KEY, algorithms=[jwt_settings.ALGORITHM], options=options)
            return payload
        except ExpiredSignatureError:
            raise AuthenticationFailed(detail="Token has expired.")
        except InvalidSignatureError:
            raise AuthenticationFailed(detail="Signature verification failed.")
        except DecodeError as e:
            raise AuthenticationFailed(detail=f"JWT decoding error: {str(e)}")
